<?php if ( ! defined('WDK_PATH')) exit('No direct script access allowed');
require_once BASE_PATH.'app/controller.php';
class User extends Controller
{
	function __construct()
	{
		parent::__construct();
		$this->_init();
	}
	
	protected function _init() 
	{
	}
	
	public function index()
	{
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$assign_data = array();
		/****************************************************************************************************************************/
		try 
		{
			$a = Wdk::get('User');
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/	
		parent::_view($assign_data);
		/****************************************************************************************************************************/
	}
	
	public function login()
	{
		if(parent::_isLogin())	parent::_redirect('/');
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$user_login_id		= (string) post('user_login_id');
		$user_login_passwd	= (string) post('user_login_passwd');
		$user				= Wdk::get('User');
		/****************************************************************************************************************************/
		try 
		{
			if(parent::_isPost())
			{
				$user->login($user_login_id, $user_login_passwd);
				$this->session->set('user_seq'				, $user['user_seq']);
				$this->session->set('user_login_id'			, $user['user_login_id']);
				$this->session->set('user_name'				, $user['user_name']);
				$this->session->set('user_nick'				, $user['user_nick']);
				$this->session->set('user_group_level'		, $user['user_group_level']);
				$this->session->set('user_group_seq'		, $user['fk_user_group_seq']);
				
				if($user['user_type'] == USER_TYPE_ADMIN)
				{
					$as = Wdk::helper('AdminSession');
					$as->set('user_seq'				, $user['user_seq']);
					$as->set('user_login_id'		, $user['user_login_id']);
					$as->set('user_name'			, $user['user_name']);
					$as->set('user_nick'			, $user['user_nick']);
				}
				
				$url = parse_url($_SERVER['HTTP_REFERER']);
				parent::_redirect($url['path']);
			}
		}
		catch(NoRecordException $e)
		{
			parent::_script(array("alert('존재하지 않는 아이디입니다.');", "history.back();"));
		}
		catch(UserPasswordException $e)
		{
			parent::_script(array("alert('비밀번호를 확인하십시오.');", "history.back();"));
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/	
		parent::_view();
		/****************************************************************************************************************************/
	}
	
	public function logout()
	{
		$this->session->destroy();
		$as = Wdk::helper('AdminSession');
		$as->destroy();
		parent::_redirect("/");
	}
	
	public function agreement()
	{
		if(parent::_isLogin())	parent::_redirect('/');
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$assign_data = array();
		/****************************************************************************************************************************/
		if(parent::_isPost())
		{
			$user_agreement = (array) post('user_agreement');
			if($user_agreement[0] === "T"&& $user_agreement[1] === "T")
			{
				$this->session->set('agreed', "T");
				parent::_redirect("/user/join");
			}
		}
		parent::_view($assign_data);
	}
	
	public function join()
	{
		if(parent::_isLogin())	parent::_redirect('/');
		$this->_join(); 
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$assign_data = array();
		/****************************************************************************************************************************/
		if($this->session['agreed'] != "T")
		{
			parent::_redirect("/user/agreement");
		}
		try 
		{
			
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/	
		parent::_view($assign_data);
		/****************************************************************************************************************************/
	}
	
	private function _join()
	{
		if(parent::_isPost() == false) return; 
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$user_login_id			= (string) post('user_login_id');
		$login_id_validation	= (string) post('login_id_validation');
		$email_validation		= (string) post('email_validation');
		$user_email				= (string) post('user_email');
		$user_login_passwd		= (string) post('user_login_passwd');
		$confirm_passwd			= (string) post('confirm_passwd');
		$user_name				= (string) post('user_name');
		$user_nick				= (string) post('user_nick');
		$user_phone				= (array) post('user_phone');
		$user_birth_date		= (array) post('user_birth_date');
		$user_mobile			= (array) post('user_mobile');
		$user_sex				= (string) post('user_sex');
		$user_memo				= (string) post('user_memo');
		$user_info_public		= (string) post('user_info_public');
		$user					= Wdk::get("User");
		/****************************************************************************************************************************/
		try
		{
			if($user_login_passwd !== $confirm_passwd)	throw new WException("비밀번호와 비밀번호 확인이 일치하지 않습니다.");
			$user['user_login_id']		= $user_login_id;
			$user['user_email']			= $user_email;
			$user['user_login_passwd']	= $user_login_passwd;
			$user['user_name']			= $user_name;
			$user['user_nick']			= $user_nick;
			$user['user_birth_date']	= implode("-", $user_birth_date);
			$user['user_phone']			= implode("-", $user_phone);
			$user['user_mobile']		= implode("-", $user_mobile);
			$user['user_sex']			= $user_sex;
			$user['user_memo']			= $user_memo;
			$user['user_info_public']	= $user_info_public;
			$user->join();
			$this->session->set('agreed', "");
			
			$email	= Wdk::helper('Email');
			$email['to'] = "{$user['user_name']}<{$user['user_email']}>";
			$email['subject'] = "<뿌잉> 회원가입 안내 이메일입니다.";
			$email['body'] = str_replace(	array('{user_name}', 'user_login_id'),
											array($user['user_name'], $user['user_login_id']),
											file_get_contents(BASE_PATH.'user/mail/join.html')
										);
			$email->send();
		}
		catch(WException $e)
		{
			parent::_script(array("alert('{$e->getMessage()}');", "history.back();"));
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/	
		parent::_redirect("/user/complete/".sha1($user['user_seq']).$user['user_seq']);
		/****************************************************************************************************************************/
	}
	
	public function complete($str='')
	{
		if(parent::_isLogin())	parent::_redirect('/');
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$assign_data = array();
		$sha1		= substr($str, 0, 40);
		$user_seq	= substr($str, 40);
		/****************************************************************************************************************************/
		try 
		{
			if(sha1($user_seq) == $sha1)
			{
				$user = Wdk::get('User');
				$user->load($user_seq);
				$assign_data['data'] = $user;
			}
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/	
		parent::_view($assign_data);
		/****************************************************************************************************************************/
	}
	
	public function check()
	{
		if(parent::_isPost() == false) exit; 
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$assign_data	= array();
		$mode			= (string) post('mode');
		$val			= (string) post('val');
		$user			= Wdk::get('User');
		/****************************************************************************************************************************/
		try
		{
			switch(strtoupper($mode))
			{
				case "USER_LOGIN_ID" :
					$user->loadByLoginId($val);
					$assign_data['msg']	= "이미 사용중인 아이디 입니다.";
					break;
				case "USER_EMAIL" :
					$user->loadByEmail($val);
					$assign_data['msg']	= "이미 사용중인 Email 입니다.";
					break;
				case "USER_NICK" :
					$user->loadByNick($val);
					if($user['user_seq'] == $this->session['user_seq']) throw new NoRecordException();
					$assign_data['msg']	= "이미 사용중인 닉네임 입니다.";
					break;
			}
			$assign_data['error'] = true;
		}
		catch(NoRecordException $e)
		{
			$assign_data['error']	= false;
			$assign_data['val']		= $val;
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/	
		return parent::_json($assign_data);
		/****************************************************************************************************************************/
	}
	
	public function find()
	{
		if(parent::_isLogin())	parent::_redirect('/');
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$assign_data	= array('error'=>true, 'msg'=>'사용자 정보가 존재하지 않습니다.');
		$mode			= (string) post('mode');
		$user_name		= (string) post('user_name');
		$user_email		= (string) post('user_email');
		$user_login_id	= (string) post('user_login_id');
		/****************************************************************************************************************************/
		try
		{
			if(parent::_isPost())
			{
				$user	= Wdk::get('User');
				try
				{
					switch(strtoupper($mode))
					{
						case "FINDID":
							$user->loadByEmail($user_email);
							if($user['user_name'] == $user_name)
							{
								$assign_data['msg']		= "회원님의 아이디는 {$user['user_login_id']} 입니다";
								$assign_data['error']	= false;
							}
							break;
						case "FINDPWD":
							$user->loadByLoginId($user_login_id);
							if($user['user_email'] == $user_email)
							{
								$email	= Wdk::helper('Email');
								$email['to'] = "{$user['user_name']}<{$user['user_email']}>";
								$email['subject'] = "뿌잉 <http://www.ppuying.com> - 비밀번호 찾기 안내메일입니다.";
								$email['body'] = str_replace(	array('{tmp_passwd}'), 
																array($user->resetPasswd()), 
																file_get_contents(BASE_PATH.'user/mail/findpwd.html')
															);
								$email->send();
								$assign_data['msg']		= "회원님의 이메일 계정으로 임시비밀번호를 발송했습니다. ";
								$assign_data['error'] = false;
							}
							break;
					}
				}
				catch(NoRecordException $e){}
				parent::_json($assign_data);
			}
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/	
		parent::_view($assign_data);
		/****************************************************************************************************************************/
	}
	
	public function info($user_login_id='')
	{
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$assign_data = array();
		$user = Wdk::get("User");
		/****************************************************************************************************************************/
		try
		{
			$user->loadByLoginId($user_login_id);
			$assign_data['data'] = $user;
		}
		catch(NoRecordException $e)
		{
			parent::_script(array("잘못된 접근입니다.", "window.close();"));
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/
		parent::_layout('popup');
		parent::_view($assign_data);
		/****************************************************************************************************************************/
	}
	
	public function myinfo()
	{
		parent::_loginCheck();
		$this->_myinfo();
		$this->_authorized();
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$assign_data = array();
		$user = Wdk::get("User");
		/****************************************************************************************************************************/
		try
		{
			$user->load($this->session['user_seq']);
			$assign_data['data'] = $user;
			$this->session->set('authorized', mktime());
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/
		parent::_view($assign_data);
		/****************************************************************************************************************************/
	}
	
	public function confirmation()
	{
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$user = Wdk::get("User");
		$user_login_passwd = (string) post('user_login_passwd');
		/****************************************************************************************************************************/
		try
		{
			if(parent::_isPost())
			{
				$user->load($this->session['user_seq']);
				$pwd = Wdk::helper('Passwd');
				if( !$pwd->isEqual($user['user_login_passwd'], $user_login_passwd))
				{
					throw new UserPasswordException();
				}
				$this->session->set('authorized', mktime());
				parent::_redirect('/user/myinfo');
			}
		}
		catch(UserPasswordException $e)
		{
			parent::_script(array("alert('비밀번호가 틀립니다.')", "history.back();"));
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/
		parent::_view();
		/****************************************************************************************************************************/
	}
	
	public function validation($code='')
	{
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$user 			= Wdk::get("User");
		$assign_data	= array();
		/****************************************************************************************************************************/
		try
		{
			if(parent::_isPost())
			{
				$user->load($this->session['user_seq']);
				$time = mktime();
				$code = array();
				$code[] = $this->session['user_seq'];
				$code[] = sha1($time.$this->session['user_seq']);
				$code[] = $time;
				$email	= Wdk::helper('Email');
				$email['to'] = "{$user['user_name']}<{$user['user_email']}>";
				$email['subject'] = "뿌잉 <http://www.ppuying.com> - 이메일 인증 요청 메일입니다..";
				$email['body'] = str_replace(	array('{url}'), 
												array("http://{$this->config['domain']}/user/validation/".implode("&", $code)),
												file_get_contents(BASE_PATH.'user/mail/validation.html')
											);
				$email->send();
				$assign_data['msg']		= "회원님의 이메일 계정으로 인증메일을 발송했습니다. ";
				parent::_json($assign_data);
			}
			else
			{
				$assign_data['code'] = 1;
				$code = explode("&", $code);
				if(count($code) != 3)
				{
					$assign_data['code'] = 9;
					$assign_data['type'] = "001";
				}
				else
				{
					if($code[1] != sha1($code[2].$code[0]))
					{
						$assign_data['code'] = 9;
						$assign_data['type'] = "002";
					}
					else
					{
						if(mktime() > $code[2]+1*60*60)
						{
							$assign_data['result'] = 3;
						}
						else
						{
							try
							{
								$user->load($code[0]);
								if($user->isApproved())
								{
									$assign_data['code'] = 2;									
								}
								else
								{
									$user->approve();
									$assign_data['data'] = $user;
								}
							}
							catch(NoRecordException $e)
							{
								$assign_data['code'] = 9;
								$assign_data['type'] = "003";
							}
						}
					}
				}
			}
		}
		catch(WException $e)
		{
			parent::_error($e);
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/
		parent::_view($assign_data);
		/****************************************************************************************************************************/
	}
	
	private function _authorized()
	{
		//	3분간 유효..
		if(array_key_exists('authorized', $this->session)
		&& $this->session['authorized'] + 3*60 > mktime())
		{
			return;
		}
		parent::_redirect('/user/confirmation');
	}
	
	private function _myinfo()
	{
		if(parent::_isPost() == false) return;
		/*****************************************************************************************************************************
		 * BASIC VARS
		*****************************************************************************************************************************/
		$user_login_passwd		= (string) post('user_login_passwd');
		$confirm_passwd			= (string) post('confirm_passwd');
		$user_nick				= (string) post('user_nick');
		$user_phone				= (array) post('user_phone');
		$user_birth_date		= (array) post('user_birth_date');
		$user_mobile			= (array) post('user_mobile');
		$user_sex				= (string) post('user_sex');
		$user_memo				= (string) post('user_memo');
		$user_info_public		= (string) post('user_info_public');
		$user					= Wdk::get("User");
		$uploader				= Wdk::helper('Uploader');
		$file_removed			= array();
		$file_to_move			= array();
		/****************************************************************************************************************************/
		try
		{
			$user->load($this->session['user_seq']);
		
			if(strlen(trim($user_login_passwd)) != '')
			{
				if($user_login_passwd !== $confirm_passwd)
				{
					throw new WException("비밀번호와 비밀번호 확인이 일치하지 않습니다.");					
				}
				$user['user_login_passwd']	= $user_login_passwd;
			}
			$user['user_nick']			= $user_nick;
			$user['user_birth_date']	= implode("-", $user_birth_date);
			$user['user_phone']			= implode("-", $user_phone);
			$user['user_mobile']		= implode("-", $user_mobile);
			$user['user_sex']			= $user_sex;
			$user['user_memo']			= $user_memo;
			$user['user_info_public']	= $user_info_public;
			/********************************************************************************/
			if(post('remove_user_icon', 'F') == 'T')
			{
				$file_removed[] = $user['user_icon'];
				$user['user_icon'] = '';
			}
			$uploader->upload_size = 15;
			$uploader->upload_exts = '.gif';
			if($uploader->load('user_icon', 'usericon'))
			{
				$file_removed[] = $user['user_icon'];
				$icon = $uploader->get('user_icon');
				$user['user_icon']	= $icon['path'];
				$file_to_move[] = $icon['path'];
			}
			/********************************************************************************/
			if(post('remove_user_photo', 'F') == 'T')
			{
				$file_removed[] = $user['user_photo'];
				$user['user_photo'] = '';
			}
			$uploader->upload_size = 30;
			$uploader->upload_exts = '.gif';
			if($uploader->load('user_photo', 'userphoto'))
			{
				$file_removed[] = $user['user_photo'];
				$icon = $uploader->get('user_photo');
				$user['user_photo']	= $icon['path'];
				$file_to_move[] = $icon['path'];
			}
			/********************************************************************************/
			$user->update();
			moveToFtp($file_to_move);
			removeFromFtp($file_removed);
			$this->session->set('user_seq'				, $user['user_seq']);
			$this->session->set('user_login_id'			, $user['user_login_id']);
			$this->session->set('user_name'				, $user['user_name']);
			$this->session->set('user_nick'				, $user['user_nick']);
			$this->session->set('user_group_level'		, $user['user_group_level']);
			$this->session->set('user_group_seq'		, $user['fk_user_group_seq']);
			/********************************************************************************/
		}
		catch(UploadFileExtsException $e)
		{
			parent::_script(array("alert('{$e->getMessage()}');", "history.back();"));
		}
		catch(UploadFileSizeException $e)
		{
			parent::_script(array("alert('업로드 크기가 15kb를 넘었습니다.');", "history.back();"));
		}
		catch(WException $e)
		{
			parent::_script(array("alert('{$e->getMessage()}');", "history.back();"));
		}
		/*****************************************************************************************************************************
		 * RESULT
		*****************************************************************************************************************************/
		parent::_script(array("alert('수정되었습니다.');", "location.href='/user/myinfo';"));
		/****************************************************************************************************************************/
	}
}